package cn.t.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import cn.t.base.TClient;

public class TMQClient implements TClient {

  private Integer port;

  private String host;

  public static void main(String[] args) throws UnknownHostException, IOException {
    new TMQClient().initClient();
  }

  @Override
  public int initClient() {

    if (this.port == null) {
      this.port = DEFAULT_PORT;
    }

    if (this.host == null) {
      this.host = DEFAULT_HOST;
    }

    try (Socket socket = new Socket(this.host, this.port);
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();) {
      String message = "hello world";
      outputStream.write(message.getBytes("UTF-8"));
      //通过shutdownOutput告诉服务器已经发送完数据，后续此客户端只能接受数据
      socket.shutdownOutput();
      byte[] bytes = new byte[1024];
      int len;
      StringBuilder sb = new StringBuilder();
      while ((len = inputStream.read(bytes)) != -1) {
        //注意指定编码格式，发送方和接收方一定要统一
        sb.append(new String(bytes, 0, len, "UTF-8"));
      }
      System.out.println("MESSAGE FROM SERVER: " + sb);

    } catch (IOException e) {
      e.printStackTrace();
    }
    return 0;
  }

}
